﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel.Composition;
using ViewMaker.Core.Utils;
using System.Xml.Serialization;
using System.IO;

namespace ViewMaker.Core.Wpf
{
    [Export(typeof(IViewLayoutPersistenceService))]
    public class WpfViewLayoutPersistenceService : ViewLayoutPersistenceService
    {
        public override string GetDefaultLayoutName(Type vmType)
        {
            return TypeUtil.GetFullTypeString(vmType).Replace("<", "[").Replace(">", "]") + ".xml";
        }

        public override void Save(ViewLayoutItem layout, string filename)
        {
            using (var st = new FileStream(filename, FileMode.Create, FileAccess.Write))
            {
                var ser = new XmlSerializer(typeof(ViewLayoutItem));
                ser.Serialize(st, layout);
            }
        }

        public override ViewLayoutItem Load(string filename)
        {
            if (!File.Exists(filename)) return null;
            using (var st = new FileStream(filename, FileMode.Open, FileAccess.Read))
            {
                var ser = new XmlSerializer(typeof(ViewLayoutItem));
                return (ViewLayoutItem)ser.Deserialize(st);
            }
        }

        public override void Delete(string filename)
        {
            if (!File.Exists(filename)) return;
            File.Delete(filename);
        }

        public override List<string> ListData()
        {
            var ser = new XmlSerializer(typeof(ViewLayoutItem));
            var result = new List<string>();
            foreach (var file in Directory.GetFiles(".", "*.xml"))
            {
                try
                {
                    // Try Deserialize
                    using (var st = new FileStream(file, FileMode.Open, FileAccess.Read))
                    {
                        ser.Deserialize(st);
                    }
                    result.Add(Path.GetFileName(file));
                }
                catch
                {
                    //ERROR FREE
                }                
            }
            return result;
        }


        public override bool Exists(string filename)
        {
            return File.Exists(filename);
        }
    }

}
